package com.wutongyu.mannyburger;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

public class RegisterFragment extends Fragment {

    private static final String TAG = "RegisterFragment";
    private EditText editTextPhone;
    private EditText editTextPassword;
    private EditText editTextConfirmPassword;
    private Spinner spinnerSecurityQuestion;
    private EditText editTextSecurityAnswer;
    private Button buttonRegister;
    private TextView textViewLogin;
    private UserDatabaseHelper dbHelper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_register, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        editTextPhone = view.findViewById(R.id.edit_text_phone);
        editTextPassword = view.findViewById(R.id.edit_text_password);
        editTextConfirmPassword = view.findViewById(R.id.edit_text_confirm_password);
        spinnerSecurityQuestion = view.findViewById(R.id.spinner_security_question);
        editTextSecurityAnswer = view.findViewById(R.id.edit_text_security_answer);
        buttonRegister = view.findViewById(R.id.button_register);
        textViewLogin = view.findViewById(R.id.text_view_login);

        // 设置密保问题下拉列表
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                requireContext(),
                R.array.security_questions,
                android.R.layout.simple_spinner_item
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSecurityQuestion.setAdapter(adapter);

        dbHelper = new UserDatabaseHelper(requireContext());

        buttonRegister.setOnClickListener(v -> attemptRegister());

        textViewLogin.setOnClickListener(v -> navigateToLogin());
    }

    private void attemptRegister() {
        String phone = editTextPhone.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        String confirmPassword = editTextConfirmPassword.getText().toString().trim();
        int securityQuestionPosition = spinnerSecurityQuestion.getSelectedItemPosition();
        String securityAnswer = editTextSecurityAnswer.getText().toString().trim();

        // 基本验证
        if (TextUtils.isEmpty(phone)) {
            editTextPhone.setError("手机号不能为空");
            editTextPhone.requestFocus();
            return;
        }
        // 可选：添加手机号格式验证 (e.g., using Patterns.PHONE.matcher(phone).matches())

        if (TextUtils.isEmpty(password)) {
            editTextPassword.setError("密码不能为空");
            editTextPassword.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(confirmPassword)) {
            editTextConfirmPassword.setError("请确认密码");
            editTextConfirmPassword.requestFocus();
            return;
        }

        if (!password.equals(confirmPassword)) {
            editTextConfirmPassword.setError("两次输入的密码不一致");
            editTextConfirmPassword.requestFocus();
            return;
        }

        // 验证密保问题和答案
        if (TextUtils.isEmpty(securityAnswer)) {
            editTextSecurityAnswer.setError("密保答案不能为空");
            editTextSecurityAnswer.requestFocus();
            return;
        }

        // 检查用户是否已存在
        if (dbHelper.isUserExists(phone)) {
            Toast.makeText(getContext(), "该手机号已被注册", Toast.LENGTH_SHORT).show();
            Log.w(TAG, "尝试注册失败，手机号已存在: " + phone);
            return;
        }

        // 添加用户到数据库
        boolean isAdded = dbHelper.addUser(phone, password, securityQuestionPosition, securityAnswer);

        if (isAdded) {
            Toast.makeText(getContext(), "注册成功！请登录。", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "用户 " + phone + " 注册成功");
            // 导航回登录界面
            navigateToLogin();
        } else {
            // addUser 内部已经处理了 isUserExists 的情况，所以这里的 else 主要是处理插入数据库时的其他错误
            Toast.makeText(getContext(), "注册失败，请稍后重试", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "用户 " + phone + " 注册失败（数据库插入错误）");
        }
    }

    private void navigateToLogin() {
        Log.d(TAG, "导航回登录 Fragment");
        FragmentManager fragmentManager = getParentFragmentManager();
        // 从后台堆栈中弹出当前 Fragment (RegisterFragment)，显示之前的 Fragment (LoginFragment)
        fragmentManager.popBackStack(); 
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
} 